package com.cloudwise.controller;

import cn.hutool.db.Page;
import com.cloudwise.entity.*;
import com.cloudwise.service.DeptService;
import com.cloudwise.service.RoleService;
import com.cloudwise.service.UserService;
import com.cloudwise.util.MyConstants;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2020-12-17 10:18:05
 */
@Controller
@RequestMapping("user")
public class UserController   extends  BaseController{
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Autowired
    DeptService deptService;
    @Autowired
    RoleService roleService;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ResponseBody
    public User selectOne(Integer id) {
        return this.userService.queryById(id);
    }
    /**
     * @create by: Teacher陈
     * @description: 跳转到显示所有用户页面
     * @create time: 2020/12/21 16:54
     */
    @RequestMapping("/toShowUser")
    public String toShowUser(Model model){
        //查询所有的部门信息，填充到页面下拉框中
        List<Dept> deptList = deptService.queryAll(null);
        //查询所有的角色信息，填充到页面下拉框中
        List<Role> roleList = roleService.queryAll(null);
        model.addAttribute("deptList", deptList);
        model.addAttribute("roleList", roleList);
        return "user/showUser";
    }

    /**
     * create by: Teacher陈
     * description: 条件查询加分页
     * create time: 2020/7/20 17:20

     */
    @RequestMapping("/selectAllUser")
    @ResponseBody
    public ReturnBean selectAllUser(PageBean pageBean, User user ){
        //计算分页参数
        int offset = calcPageParam(pageBean);
        List<UserVo> userList = userService.queryAllUserVoByConditionAndLimit(user,offset, pageBean.getLimit());
        long count = userService.getCount(user);
        //返回json结果
        ReturnBean returnBean = returnSuccess(userList);
        returnBean.setCount(count);
        return returnBean;

    }


    /**
     * create by: Teacher陈
     * description: 判断用户名是否存在，存在的话返回false，不存在返回true
     * create time: 2020/7/22 17:08
     *
     * @Param: username
     * @return boolean
     */
    @RequestMapping("/checkUserName")
    @ResponseBody
    public ReturnBean checkUserName(String username){
        User user = userService.queryByUsername(username);
        if (user != null) {
            return  returnFailMessage(user,"用户名已经存在");
        }
        return returnSuccess(user);
    }


    /**
     * create by: Teacher陈
     * description: 保存用户
     * create time: 2020/7/23 15:43
     *
     * @return a
     * @Param: null
     */
    @RequestMapping("/saveUser")
    @ResponseBody
    public ReturnBean saveUser(User user){
        user = setCreate(user);
        user.setDelFlag("0");
        boolean insert = userService.saveUserAndSalt(user);
        if(insert){
            return returnSuccess(null);
        }
        return returnFail(null);
    }
    @RequestMapping("/updateUser")
    @ResponseBody
    /**
     * @create by: Teacher陈
     * @description: 修改用户
     * @create time: 2020/7/18 19:32
     * @param user
     * @return com.aaa.entity.Result
     */
    public ReturnBean updateUser(User user){
        user = setUpdate(user);
        boolean update = userService.updateUserAndSalt(user);
        if(update){
            return returnSuccess(null);
        }
        return returnFail(null);
    }
    /**
     * @create by: Teacher陈
     * @description: 删除用户（逻辑删除）
     * @create time: 2020/7/19 13:44
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public ReturnBean deleteUser(User user){
        try {
            //创建人，创建时间
            user = setUpdate(user);
            user.setDelFlag("1");
            User user1 = userService.update(user);
            return returnSuccess(user1);
        }catch (Exception e){
            return returnFail(null);
        }
    }
    /**
     * @create by: Teacher陈
     * @description: 根据用户id查询自己的角色
     * @create time: 2020/7/18 21:28
     */
    @RequestMapping("/getRoleCheckByUserId")
    @ResponseBody
    public ReturnBean getRoleCheckByUserId(Integer userId){
        List<Role> roleUserList = roleService.selectListByUserId(userId);
        List<Role> roleList = roleService.queryAll(null);
        Map map = new HashMap();
        for (Role role : roleList) {
            //判断集合包含对象，必须重写equals和hashcode方法
            if(roleUserList.contains(role)){
                map.put(role.getRoleKey(), true);
            }else {
                map.put(role.getRoleKey(), false);
            }
        }
        return returnSuccess(map);
    }

    /**
     * @create by: Teacher陈
     * @description: 重置密码
     * @create time: 2020/7/19 15:16
     */
    @RequestMapping("/resetPassword")
    @ResponseBody
    public  ReturnBean resetPassword(User user){
        user=setUpdate(user);
        boolean update = userService.resetPassword(user);
        if(update){
            return returnSuccess(null);
        }
        return returnFail(null);
    }
    /**
     * @create by: Teacher陈
     * @description: 批量删除用户
     * @create time: 2020/7/19 15:20
     * @param userList
     * @return Result
     */
    @RequestMapping(value = "/deleteBatchUser")
    @ResponseBody
    public ReturnBean deleteBatchUser(@RequestBody List<User> userList) {
        List<User> userListNew = new ArrayList<>();
        //此处是逻辑删除，修改delflag
        for (User user : userList) {
            User userNew = new User();
            userNew.setDelFlag("1");
            userNew.setUserId(user.getUserId());
            userListNew.add(userNew);
        }
        boolean update = userService.updateBatchById(userListNew);
        if (update) {
            return returnSuccess(null);
        } else {
            return returnFail(null);
        }
    }

    @RequestMapping("/toBasicInformation")
    public String toBasicInformation(Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user",user);
        return "user/userInfo";
    }

    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public  ReturnBean updateUserInfo(User user){
        try {
            //创建人，创建时间
            user = setUpdate(user);
            userService.update(user);
            return returnSuccess(null);
        }catch (Exception e){
            return returnFail(null);
        }

    }
}